function convertStringToAscii(str: string): number[] {
  return Array.from(str, (char) => char.charCodeAt(0));
}

export function stringToWords(str: string): number[] {
  const asciiArray = convertStringToAscii(str);
  const paddedLength = Math.ceil(asciiArray.length / 2) * 2;
  const buffer = Buffer.alloc(paddedLength);
  asciiArray.forEach((code: any, i: number) => (buffer[i] = code & 0xff)); // Fill ASCII, pad with 0s

  const words: number[] = [];
  for (let i = 0; i < buffer.length; i += 2) {
    words.push(buffer.readInt16LE(i));
  }
  return words;
}

export function decodeStringFromWords(words: number[]): string {
  const bytes: number[] = words.flatMap((word) => [
    word & 0xff, // Low byte (first char)
    (word >> 8) & 0xff, // High byte (second char)
  ]);
  let str = String.fromCharCode(...bytes);
  // Remove trailing nulls and whitespace
  str = str.replace(/\0.*$/, "").trimEnd();
  return str;
}
